#include "TreeDirectoryInterface.h"

#include <QHBoxLayout>
#include <qheaderview.h>
#include <QKeyEvent>
#include <QDebug>
#include <QApplication>
#include <QPushButton>

#define status_index 24
#define ParentTreeID 25
#define NoneParent 9999



TreeDirectoryInterface::TreeDirectoryInterface(QWidget *treeWidget, WavePlotInterface &wavePlotInf, QMap<int, QString> &electrodeMap, QWidget *parent):
    m_treeWidget(treeWidget),
	fri_wavePlotInf(wavePlotInf),
	electrodeNameMap(electrodeMap),
	QWidget(parent)
{   
    // _menu = new QMenu(_leftTree);
	// _menu->addAction("通道详情");

	// connect(_menu, &QMenu::triggered, this, &TreeDirectoryInterface::menuAction);
	btn_serchItem = m_treeWidget->findChild<QPushButton*>("btn_serch");
	edit_serchItem = m_treeWidget->findChild<QLineEdit*>("edit_serch");
	// 设置焦点到按键上，避免一打开窗口就搜索
	btn_serchItem->setFocus();
	// edit_serchItem->clearFocus();

    initTree();
	initMap();
    connect(_leftTree, SIGNAL(itemPressed(QTreeWidgetItem*, int)), this, SLOT(tree_itemPressed(QTreeWidgetItem*, int)));
	connect(_leftTree, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(tree_itemDoubleClicked(QModelIndex)));
	connect(_leftTree, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this, SLOT(tree_itemChanged(QTreeWidgetItem*, int)));
	connect(btn_serchItem, SIGNAL(clicked(bool)), this, SLOT(btn_expandingTreeNode(bool)));
	connect(edit_serchItem, &QLineEdit::editingFinished, this, &TreeDirectoryInterface::serchTextChanged);

	// std::cout << "electrodeNameMap[\"FP1\"]" << electrodeNameMap[EEGDEV::FP1].toStdString() << std::endl;
}
TreeDirectoryInterface::~TreeDirectoryInterface()
{
    if (_menu)
	{
		_menu->clear();
		delete _menu;
		_menu = nullptr;
	}
}

/**********************************
 * 函数名：TreeDirectoryWidget::initTreeData
 * 功能：初始化树的节点信息
 * 输入：无
 * 输出：无
 * 备注：无
**********************************/
void TreeDirectoryInterface::initMap()
{
	// 使用友元类，绑定wavePlot的参数
	uint8_t channalNum = fri_wavePlotInf.m_countGraph;

	for(auto channalIndex : electrodeNameMap.keys()){
		auto data = std::make_shared<DevStationData>();
		data->setType("BRE_Dev");
		data->setDevName(electrodeNameMap[channalIndex] + " (" + QString::number(channalIndex+1) + ")");
		data->setDevCode(QString::number(channalIndex+1));
		devMap.insert(channalIndex, data);
	}

	QMap<QString, QString> treeIdmap;    //type和id
	// if (this){
		for (auto& pair : devMap.toStdMap()){
			auto channel = pair.first;
			auto data = pair.second;
			QString code = data->getDevCode();
			QString type = data->getType();
			if (treeIdmap.contains(type)){
				QString Treeid = treeIdmap.value(type);
				// qDebug() << "Treeid:" << Treeid;
				this->CreateChildLeafNode(static_cast<TreeItemInfo*>(data.get()), Treeid);
				//_treeWidget->setLeafNodeCheck(code,true);
			}
			else{
				QString treeId = this->CreateRootLeafNode(type);
				this->CreateChildLeafNode(static_cast<TreeItemInfo*>(data.get()), treeId);
				treeIdmap.insert(type, treeId);
			}
		}
	// }
}

void TreeDirectoryInterface::initTree()
{
	QWidget* menuWidget = m_treeWidget->findChild<QWidget*>("menuWidget");
	if (scroll == NULL)
		scroll = new QScrollArea(menuWidget);
	scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
	scroll->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
	scroll->resize(menuWidget->width(), menuWidget->height());
	scroll->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
	if (_leftTree == NULL)
		_leftTree = new QTreeWidget(scroll);
	_leftTree->header()->hide();
	QHBoxLayout* layout = new QHBoxLayout();
	layout->setContentsMargins(0, 0, 0, 0);
	layout->addWidget(_leftTree);
	menuWidget->setLayout(layout);
	_leftTree->setGeometry(0, 0, scroll->width(), scroll->height());
	// 设置缩进像素为4，减少左边的留空
	_leftTree->setIndentation(4);

	// 打开所有选项
	// _leftTree->setExpanded(false);
	
}


void TreeDirectoryInterface::tree_itemPressed(QTreeWidgetItem* item, int column)
{
	if (qApp->mouseButtons() == Qt::RightButton)
	{
		if (_menu)
			_leftTree->addActions(_menu->actions());
		_leftTree->setContextMenuPolicy(Qt::ActionsContextMenu);
	}
}

void TreeDirectoryInterface::tree_itemDoubleClicked(const QModelIndex& index)
{
	if (_leftTree)
	{
		QList<QTreeWidgetItem*> selects = _leftTree->selectedItems();
		if (selects.count() > 0)
		{
			QString str = selects.at(0)->data(0, Qt::UserRole + 9).toString();
			qDebug() << "checkbox double click：" << str;
			emit sig_itemDoubliClicked(str);
		}

	}
}

void TreeDirectoryInterface::tree_itemChanged(QTreeWidgetItem* item, int column)
{
	//获取节点勾选状态时要发送的信息
	if (item)
	{
		for (int i = 0; i < item->childCount(); i++)
		{
			item->child(i)->setCheckState(0, item->checkState(0));
		}
		bool check = item->checkState(0) == Qt::Checked ? true : false;
		QString str = item->data(0, Qt::UserRole + 5).toString();
		QString id = item->data(0, Qt::UserRole + 10).toString();    //QVariant 通用类型
		if (id.isEmpty())
			return;
		// 隐藏曲线
		fri_wavePlotInf.wavePlot->graph(id.toInt()-1)->setVisible(check);
		// emit sig_itemCheckChange(id, check);
		// qDebug() << " checkbox item change: " << str << "  id=" << id << " check=" << check;

	}
}

void TreeDirectoryInterface::btn_expandingTreeNode(bool){
	search();
}

void TreeDirectoryInterface::serchTextChanged(){
	search();
}


void TreeDirectoryInterface::menuAction(QAction* action)
{
	// if (_menu == nullptr)
	// 	return;
	// if (action->text() == ("通道详情"))
	// {
	// 	if (_leftTree)
	// 	{
	// 		QList<QTreeWidgetItem*> selects = _leftTree->selectedItems();
	// 		if (selects.count() > 0)
	// 		{
	// 			QString str = selects.at(0)->data(0, Qt::UserRole + 9).toString();
	// 			qDebug() << "checkbox selected right key: " << str;
	// 			emit sig_itemMenuClick(str);
	// 		}
	// 	}
	// }
}


/**********************************
 * 函数名：search
 * 功能：搜索通道
 * 输入：无
 * 输出：无
 * 备注：无
**********************************/
void TreeDirectoryInterface::search()
{
	QString text = edit_serchItem->text();
	if (text.isEmpty() || text.isNull())
	{
		for (auto item : _treeItemMap.values())
		{
			item->setHidden(false);
			item->setExpanded(false);   //是否展开每一项
		}
		scroll->hide();
		return;
	}
	else
	{
		for (QString countryNmae : _treeItemMap.keys())
		{
			if (countryNmae.contains(text))
			{
				auto rootItem = _treeItemMap.value(countryNmae);
				if (rootItem)
				{
					rootItem->setHidden(false);
					scroll->show();
				}
			}
			else
			{
				_treeItemMap.value(countryNmae)->setHidden(true);
				scroll->hide();
			}
		}
		for (QString leafname : _treeNameMap.keys())
		{
			if (leafname.contains(text))
			{
				auto leafItem = _treeNameMap.value(leafname);
				auto _parent = dynamic_cast<QTreeWidgetItem*>(leafItem->parent());
				for (auto item : _treeItemMap.values())
				{
					if (item == _parent)
					{
						item->setHidden(false);
						item->setExpanded(true);
					}
				}
				leafItem->setHidden(false);
				scroll->show();
			}
			else
			{
				_treeNameMap.value(leafname)->setHidden(true);
				scroll->hide();
			}
		}
	}
}

QString TreeDirectoryInterface::CreateRootLeafNode(QString name, QString pid)
{
	if (pid == NULL)  //创建根节点
	{
		if (_leftTree == NULL)
			initTree();
		rootTreeItem = new QTreeWidgetItem(_leftTree);
		rootTreeItem->setText(0, name);  //0或1
		// rootTreeItem->setCheckState(0, Qt::Checked);
		rootTreeItem->setCheckState(0, Qt::Checked);
		//_leftTree->addTopLevelItem(rootTreeItem);
		_leftTree->expandItem(rootTreeItem);    //展开节点
		QString rootId = QString::number(index++) + name;
		_treeItemMap.insert(rootId, rootTreeItem);
		rootTreeItem->setData(0, Qt::UserRole + 5, rootId);  
		rootTreeItem->setData(0, Qt::UserRole + 6, name);  
		rootTreeItem->setData(0, Qt::UserRole + ParentTreeID, NoneParent);
		rootTreeItem->setData(0, Qt::UserRole + status_index, 99);
		return rootId;
	}
	else    //创建叶子结点
	{
		if (_treeItemMap.contains(pid))
		{
			auto item = _treeItemMap.value(pid);
			rootTreeItem = new QTreeWidgetItem(item);
			rootTreeItem->setCheckState(0, Qt::Checked);
			rootTreeItem->setText(0, name);


			QString rootId = QString::number(index++) + name;
			_treeItemMap.insert(rootId, rootTreeItem);
			_treeNameMap.insert(name, rootTreeItem);
			rootTreeItem->setData(0, Qt::UserRole + 5, rootId);   
			rootTreeItem->setData(0, Qt::UserRole + 6, name);   
			rootTreeItem->setData(0, Qt::UserRole + ParentTreeID, pid);
			rootTreeItem->setData(0, Qt::UserRole + status_index, 99);
			return rootId;
		}
		else
			return NULL;
	}
}

bool TreeDirectoryInterface::CreateChildLeafNode(TreeItemInfo* info, QString pid)
{
	if (info == NULL)
		return false;
	if (pid != NULL) //存在创建子节点
	{
		if (_treeItemMap.contains(pid))
		{
			auto item = _treeItemMap.value(pid);    //获取父节点
			LeafTreeItem = new QTreeWidgetItem(item);
			LeafTreeItem->setText(0, info->GetTreeItemName());
			LeafTreeItem->setTextColor(0, info->GetStatusColor());
			int count = item->childCount();
			QString txt = item->data(0, Qt::UserRole + 6).toString();
			item->setText(0, txt + "(" + QString::number(count) + ")");

			_treeItemMap.insert(info->GetTreeItemID(), LeafTreeItem);
			_treeNameMap.insert(info->GetTreeItemName(), LeafTreeItem);
			//leaftreeitem->setMenu(_menu);

			LeafTreeItem->setData(0, Qt::UserRole + 5, info->GetTreeItemID());   
			LeafTreeItem->setData(0, Qt::UserRole + 6, info->GetTreeItemName());   
			LeafTreeItem->setData(0, Qt::UserRole + 9, info->GetDoubleClickCode());
			LeafTreeItem->setData(0, Qt::UserRole + 10, info->GetCheckChangeCode());
			LeafTreeItem->setData(0, Qt::UserRole + ParentTreeID, pid);
			LeafTreeItem->setData(0, Qt::UserRole + status_index, info->statusIndex);
			//            if(info->GetCheckAble())
			//            {
			//                LeafTreeItem->setCheckState(0,info->checkstate);
			//            }
			//            else
			LeafTreeItem->setCheckState(0, Qt::Checked);
			return true;
		}
		else
			return false;
	}
	else
	{
		LeafTreeItem = new QTreeWidgetItem(_leftTree);
		LeafTreeItem->setText(0, info->GetTreeItemName());
		_treeItemMap.insert(info->GetTreeItemID(), LeafTreeItem);

		LeafTreeItem->setData(0, Qt::UserRole + 5, info->GetTreeItemID());   //存在通用变量中
		LeafTreeItem->setData(0, Qt::UserRole + 6, info->GetTreeItemName());
		LeafTreeItem->setData(0, Qt::UserRole + 9, info->GetDoubleClickCode());
		LeafTreeItem->setData(0, Qt::UserRole + 10, info->GetCheckChangeCode());
		LeafTreeItem->setData(0, Qt::UserRole + ParentTreeID, NoneParent);
		LeafTreeItem->setData(0, Qt::UserRole + status_index, info->statusIndex);

		_leftTree->addTopLevelItem(LeafTreeItem);
		//        if(info->GetCheckAble())
		//        {
		//            LeafTreeItem->setCheckState(0,info->checkstate);
		//        }
		//        else
		LeafTreeItem->setCheckState(0, Qt::Checked);
		return true;
	}
}